package tfln;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.*;

import net.rim.blackberry.api.browser.Browser;
import net.rim.blackberry.api.browser.BrowserSession;
import net.rim.blackberry.api.browser.URLEncodedPostData;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.servicebook.ServiceBook;
import net.rim.device.api.servicebook.ServiceRecord;
import net.rim.device.api.system.*;
import net.rim.device.api.xml.parsers.*;

import org.w3c.dom.*;
import org.xml.sax.*;

//import tfln.TFLNScreen.AnimatedGIFField;

import me.regexp.*;

	public class TFLN extends UiApplication {
		public static void main(String[] args) {
		TFLN theApp = new TFLN();
		theApp.enterEventDispatcher();
		}
		public TFLN() {
			
			mainScreen main = new mainScreen();
			pushScreen(main);
		}
		
		
		
	}
	
	class MyRichTextField extends RichTextField {
		
		public MyRichTextField(String text){
			super(text);
		}
		
		public MyRichTextField(String text, long style){
			super(text, style);
		}
		
		public void paint(Graphics graphics) {
    	    graphics.setColor(Color.WHITE);
    	    super.paint(graphics);
    	  }
	}
	
	class TextLabelField extends LabelField {
		
		XYRect focusRect;
		public TextLabelField(String text){
			super(text);
		}
		
		public TextLabelField(String text, long style){
			super(text, style);
		}
		
        protected void onFocus(int direction) {
            if ( focusRect == null ) {
                focusRect = this.getExtent();
            }
            super.onFocus(direction);
        }
        public boolean isSelectable() {
            return false;
        }
        
        public boolean isSelectionCopyable() {
        	return false;
        }
        
        protected void drawFocus(Graphics g, boolean on) {
            if ( focusRect != null ) {
           	 super.drawHighlightRegion(g, Field.HIGHLIGHT_FOCUS, on, 0, 0, focusRect.width, focusRect.height);                    
            } 
            else {
                super.drawFocus(g, on);                    
            }
        }
        public void getFocusRect(XYRect rect) {
            if ( focusRect == null ) {
                super.getFocusRect(rect);
            }
            else {
                rect.x = 0;
                rect.y = 0;
                rect.width = focusRect.width;
                rect.height = focusRect.height;
            }                 
        }            
        public int moveFocus(int amount, int status, int time) {
            return amount;
        }
        
        public void paint(Graphics graphics) {
       	    graphics.setColor(Color.WHITE);
       	    super.paint(graphics);
       	  }
	}
       
	
	final class aboutScreen extends TFLNScreen {
		
		private static final String version = "0.95.1";

		public aboutScreen() {
			Bitmap objHeaderImage = Bitmap.getBitmapResource("tflnberrytitle.png");
			BitmapField objHeader   = new BitmapField(objHeaderImage);
			
			HorizontalFieldManager tManager = new HorizontalFieldManager(USE_ALL_WIDTH | NON_FOCUSABLE) {
				protected void paintBackground(Graphics graphics) {

					graphics.setBackgroundColor(0x000000);
					graphics.clear();
					super.paint(graphics);
				}
			};
			tManager.add(objHeader);
			tManager.add(new MyRichTextField("About TFLNBerry", Field.NON_FOCUSABLE));
			setTitle(tManager);
			
			add(new MyRichTextField("Copyright \u00a9 2009 Blazing Wolf Computer Services"));
			add(new ActiveRichTextField("http://BlazingWolf.com"){
				public void paint(Graphics graphics) {
		    	    graphics.setColor(Color.WHITE);
		    	    super.paint(graphics);
		    	  }
			});
			add(new SeparatorField());
			add(new MyRichTextField("TFLNBerry Version: "+version));
			
			add(new SeparatorField());
			add(new MyRichTextField("Feedback:"));
			add(new ActiveRichTextField("Email: webmaster@blazingwolf.com"){
				public void paint(Graphics graphics) {
		    	    graphics.setColor(Color.WHITE);
		    	    super.paint(graphics);
		    	  }
			});
			add(new ActiveRichTextField("Twitter: @Blazing_Wolf"){
				public void paint(Graphics graphics) {
		    	    graphics.setColor(Color.WHITE);
		    	    super.paint(graphics);
		    	  }
			});
		}

    		
	}
	
	final class mainScreen extends TFLNScreen {
		
		public mainScreen() {
			Bitmap objHeaderImage = Bitmap.getBitmapResource("tflnberrytitle.png");
			BitmapField objHeader   = new BitmapField(objHeaderImage);
			
			HorizontalFieldManager tManager = new HorizontalFieldManager(USE_ALL_WIDTH | NON_FOCUSABLE) {
				protected void paintBackground(Graphics graphics) {

					graphics.setBackgroundColor(0x000000);
					graphics.clear();
					super.paint(graphics);
				}
			};
			tManager.add(objHeader);
			tManager.add(new MyRichTextField("TFLNBerry Main", Field.NON_FOCUSABLE));
			setTitle(tManager);
			loadparse();
		}
		
		public boolean keyChar(char key, int status, int time) {
					
			if (key == 'r'){
				_tcontainer.deleteAll();
				_container.delete(_tcontainer);
    			loadparse();
    			return true;
			}
			else{
		        return super.keyChar(key, status, time); 
			}
		}
		
		private void loadparse(){
			//MyRichTextField _status = new MyRichTextField("Loading");
			AnimatedGIFField load= new AnimatedGIFField((GIFEncodedImage)(GIFEncodedImage.getEncodedImageResource( "loader.gif" )),AnimatedGIFField.FIELD_LEFT);
			add(load);
	        new parse("http://feeds.feedburner.com/tfln", load).start();
			//new parse("http://textsfromlastnight.com/feed", load).start();
		}
	
	    	
		protected void makeMenu(Menu menu, int instance) {
			if (instance == Menu.INSTANCE_DEFAULT) {
				menu.add(_refresh);
	    		menu.add(_areacode);
	    	}
    		if (instance == Menu.INSTANCE_CONTEXT) {
    			menu.add(getLeafFieldWithFocus().getContextMenu());
        	}
    		super.makeMenu(menu, instance);
    	}
    	
    	public void close() {
            super.close();
		}
		
    	private MenuItem _refresh = new MenuItem("Refresh", 110, 10) {
    		public void run() {
    			_tcontainer.deleteAll();
    			_container.delete(_tcontainer);
    			loadparse();
    		}
    		};
    		
		protected MenuItem _areacode = new MenuItem("Area Code", 110, 10) {
    		public void run() {
    			
    			final CodeDialog diag;
    			String choices[] = {"Ok","Cancel"};
    			int values[] = {Dialog.OK,Dialog.CANCEL};
    			diag = new CodeDialog(choices,values);
    			UiApplication.getUiApplication().invokeLater(new Runnable() { 
    				public void run() { 
    				int iResponse = diag.doModal();
    				if(iResponse == Dialog.OK) {
    					UiApplication.getUiApplication().pushScreen(new codeScreen(diag.getAcodeField()));
    				}
    			}
    		
    			});	

    		}
    	};
    		
	}
	
	final class codeScreen extends TFLNScreen {
		String acode;
		
		public codeScreen(String areacode) {
			acode = areacode;
			Bitmap objHeaderImage = Bitmap.getBitmapResource("tflnberrytitle.png");
			BitmapField objHeader   = new BitmapField(objHeaderImage);
			
			HorizontalFieldManager tManager = new HorizontalFieldManager(USE_ALL_WIDTH | NON_FOCUSABLE) {
				protected void paintBackground(Graphics graphics) {

					graphics.setBackgroundColor(0x000000);
					graphics.clear();
					super.paint(graphics);
				}
			};
			tManager.add(objHeader);
			tManager.add(new MyRichTextField("TFLNBerry (" + acode + ")", Field.NON_FOCUSABLE));
			setTitle(tManager);
			loadparse();
		}
		
		public boolean keyChar(char key, int status, int time) {
						
			if (key == 'r'){
				_tcontainer.deleteAll();
				_container.delete(_tcontainer);
    			loadparse();
    			return true;
			}
			else{
		        return super.keyChar(key, status, time); 
			}
		}
		
		private void loadparse(){
			//MyRichTextField _status = new MyRichTextField("Loading...");
			AnimatedGIFField load= new AnimatedGIFField((GIFEncodedImage)(GIFEncodedImage.getEncodedImageResource( "loader.gif" )),AnimatedGIFField.FIELD_LEFT);
			add(load);
	        String fullurl = "http://www.textsfromlastnight.com/areacode/"+acode+"/feed/";
	        new parse(fullurl, load).start();
		}
		
		
		protected void makeMenu(Menu menu, int instance) {
			if (instance == Menu.INSTANCE_DEFAULT) {
				menu.add(_refresh);
	    		menu.add(_areacode);
	    		
	    	}
    		if (instance == Menu.INSTANCE_CONTEXT) {
    		
    			menu.add(getLeafFieldWithFocus().getContextMenu());
    		
        	}
    		super.makeMenu(menu, instance);
    	}
    	
    	public void close() {
            super.close();
		}
    	
    	
    	protected MenuItem _refresh = new MenuItem("Refresh", 110, 10) {
    		public void run() {
    			_tcontainer.deleteAll();
    			_container.delete(_tcontainer);
    			loadparse();
    		}
    		};
    		
		protected MenuItem _areacode = new MenuItem("Area Code", 110, 10) {
    		public void run() {
    			
    			final CodeDialog diag;
    			String choices[] = {"Ok","Cancel"};
    			int values[] = {Dialog.OK,Dialog.CANCEL};
    			diag = new CodeDialog(choices,values);
    			UiApplication.getUiApplication().invokeLater(new Runnable() { 
    				public void run() { 
    				int iResponse = diag.doModal();
    				if(iResponse == Dialog.OK) {
    					UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());
    					UiApplication.getUiApplication().pushScreen(new codeScreen(diag.getAcodeField()));
    				}
    			}
    		
    			});	

    		}
    	};
		
	}
	
    class TFLNScreen extends MainScreen {
        
    	protected TextLabelField top, bottom;
		protected VerticalFieldManager _container;
		protected VerticalFieldManager _tcontainer;
    	
    	public TFLNScreen() {
    		super( Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR );
    		
    	VerticalFieldManager internalManager = new VerticalFieldManager( Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR ) {
            public void paintBackground( Graphics g ) {
                g.clear();
                int color = g.getColor();
                g.setColor( 0x000000 );
                g.fillRect( 0, 0, Display.getWidth(), Display.getHeight() );
                g.setColor( color );
            }
            protected void sublayout( int maxWidth, int maxHeight ) {
                Field titleField = getMyTitleField();
                int titleFieldHeight = 0;
                if ( titleField != null ) {
                    titleFieldHeight = titleField.getHeight();
                }
                
                int displayWidth = Display.getWidth();
                int displayHeight = Display.getHeight();
    
                super.sublayout( displayWidth, displayHeight - titleFieldHeight );
                setExtent( displayWidth, displayHeight - titleFieldHeight );
            }
               
        };
        _container = new VerticalFieldManager(Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR);
        internalManager.add( _container );
        super.add( internalManager );
        _tcontainer = new VerticalFieldManager(Manager.VERTICAL_SCROLL | Manager.VERTICAL_SCROLLBAR);
    }
    	
    	public boolean keyChar(char key, int status, int time) {
    		super.keyChar(key, status, time);
			if (key == 't'){
				top.setFocus();
				return true;
			}
			else if (key == 'b'){
				bottom.setFocus();
				return true;
			}
			else{
		        return super.keyChar(key, status, time); 
			}
		}
    	
    	
    	protected void makeMenu(Menu menu, int instance) {
			if (instance == Menu.INSTANCE_DEFAULT) {
				if (getScreen().getClass().getName().compareTo("tfln.aboutScreen")!=0){
				menu.add(_about);
				}
	    	}
			super.makeMenu(menu, instance);
    	}
    	
    	protected MenuItem _about = new MenuItem("About", 110, 10) {
			public void run() {
				UiApplication.getUiApplication().pushScreen(new aboutScreen());
			}
			};
    	
    	
		protected MenuItem _close = new MenuItem("Close", 110, 10) {
			public void run() {
				System.exit(0);
			}
			};
    	
    	public void add( Field field ) {
            _container.add( field );
        }
    	
    	private Field getMyTitleField() {
            Manager delegate = getDelegate();
            Field titleField = null;
            try {
                titleField = delegate.getField( 0 );
            }
            catch ( IndexOutOfBoundsException ioobe ) {
                //
            }
            return titleField;
        }
    	
    	private boolean hasService() {
    		
 		   if(DeviceInfo.isSimulator()) {
 			   return true;
 		   }

 		   if (CoverageInfo.isOutOfCoverage()) {
 		      return false;
 		   }
 		   else {
 		      return true;
 		   }
    	}
    	
    	private static String getConnectionString()
    	{
    		//The Device is a simulator --> TCP
    		if (DeviceInfo.isSimulator())
    			return ";deviceside=true;ConnectionTimeout=20000";

    		String st = "";
    		
    		//Check wifi
    		if ( (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) &&
    			      RadioInfo.areWAFsSupported(RadioInfo.WAF_WLAN)) {
    			    st=";interface=wifi";
    		}
    		
    		//A carrier is providing us with the data service
    		if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_CARRIER) == CoverageInfo.COVERAGE_CARRIER)
    		{
    		
    			// blackberry internet service
    			ServiceRecord rec = getBIBSRecord();
    			if (rec == null)//couldn't find the right record
    				st = ";deviceside=true";// let the phone try to do the work
    			else//found the record, get the id
    				st = ";deviceside=false;connectionUID=" + rec.getUid()
    						+ ";ConnectionType=mds-public";
    		}
    		else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
    			st = ";deviceside=false";// use the clients blackberry enterprise server
    		else
    			st = ";deviceside=true";// let the phone do the work if it can

    		return st + ";ConnectionTimeout=45000";
    	}

    	//gets the record referring to the BIS configuration
    	private static ServiceRecord getBIBSRecord()
    	{
    		ServiceRecord[] ippps = ServiceBook.getSB().getRecords();
    		for (int i = 0; i < ippps.length; i++)
    		{
    			if (ippps[i].getCid().equals("IPPP"))
    			{
    				if (ippps[i].getName().indexOf("BIBS") >= 0)
    					return ippps[i];
    			}
    		}
    		return null;
    	}
    	
    	private void addfield(final String desc, final String link, final int i, final int length){
    		TextLabelField entry;
            if (i%2 == 0) {
            entry = new TextLabelField(desc, Field.FOCUSABLE | Field.READONLY | Field.USE_ALL_WIDTH) {

            
                private MenuItem _link = new MenuItem("Open in Browser", 1, 1) {
        			public void run() {
        				BrowserSession site = Browser.getDefaultSession();
        		        site.displayPage(link) ;
        			}
        			};
        			
    			private MenuItem _copy = new MenuItem("Copy", 1, 1) {
        			public void run() {
        				String text = getLeafFieldWithFocus().toString();
        				Clipboard.getClipboard().put(text);
        			}
        			};
        			
    			protected void makeContextMenu(ContextMenu menu) {
    	            menu.addItem(_link);
    	            menu.addItem(_copy);
    	        }
    			
             };
            }
            else {
           	 entry = new TextLabelField(desc, Field.FOCUSABLE | Field.READONLY | Field.USE_ALL_WIDTH) {
                    
           		 public void paintBackground( Graphics g ) {
                        g.clear();
                        int color = g.getColor();
                        g.setColor( 0x333333 );
                        g.fillRect( 0, 0, getWidth(), getHeight() );
                        g.setColor( color );
                    }
                
                    private MenuItem _link = new MenuItem("Open in Browser", 1, 1) {
            			public void run() {
            				BrowserSession site = Browser.getDefaultSession();
            		        site.displayPage(link) ;
            			}
            			};
            			
        			private MenuItem _copy = new MenuItem("Copy", 1, 1) {
            			public void run() {
            				String text = getLeafFieldWithFocus().toString();
            				Clipboard.getClipboard().put(text);
            			}
            			};
            			
        			protected void makeContextMenu(ContextMenu menu) {
        	            menu.addItem(_link);
        	            menu.addItem(_copy);
        	        }
           		 
                 }; 
           	}
            
            if (i==0) {
          	  top = entry;
             }
            if (i==length-1) {
          	  bottom = entry;
             }
            
            _tcontainer.add(entry);
            
            if (i!=length-1) {
            	_tcontainer.add(new SeparatorField());
               }
    	}
    	
    class parse extends Thread {
    	String url;
    	RichTextField status;
    	AnimatedGIFField loader;
    	
    	public parse(String u, AnimatedGIFField load) {
    		super();
    		url = u;
    		loader = load;
    	}
    
    	
    	public void run() {
	    		if (hasService()){
	    		Document doc;
	    		final String connString = getConnectionString();
	    		try {
	    			HttpConnection oCon = (HttpConnection)Connector.open(url+connString);
		    		InputStream in = oCon.openInputStream();
	        		                        
	        		int cl = (int)oCon.getLength();
	    			String returnContent;
					if (cl > 0)
	        		 {
	        		    byte[] buf = new byte[cl];
	        		    in.read(buf);
	        		    returnContent = new String(buf);
	        		 }
	        		 else
	        		 {
	        		    StringBuffer sb = new StringBuffer();
	        		    byte[] buf = new byte[1024];
	        		    int n = 0;
	        		                            
	        		    while ((n = in.read(buf)) > 0)
	        		    {
	        		       sb.append(new String(buf,0,n));
	        		    }
	        		    returnContent = sb.toString();
	        		 }
	    			
					if (returnContent.indexOf("feedburner") != -1) {
						RE f = new RE("&amp;");
						returnContent = f.subst(returnContent, "&");
					}
					else {
						RE f = new RE("(&)([^;]*?)[\\s]+?");
						returnContent = f.subst(returnContent, "$1amp;$2 ",RE.REPLACE_BACKREFERENCES);
					}
					
					StringReader reader = new StringReader( returnContent );
					InputSource inputSource = new InputSource( reader );
					
	    			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory. newInstance();
	    			docBuilderFactory.setCoalescing(true);
	    			docBuilderFactory.setExpandEntityReferences(true);
	    		     DocumentBuilder docBuilder	= docBuilderFactory.newDocumentBuilder();
	    		     
	    		     doc = docBuilder.parse(inputSource);
	    		     doc.getDocumentElement ().normalize ();
	    		     final NodeList list=doc.getElementsByTagName("item");
	    		     //this "for" loop is used to parse through the
	    		     //XML document and extract all elements and their
	    		     //value, so they can be displayed on the device
	    		     final int length = list.getLength();
	    		     UiApplication.getUiApplication().invokeLater (new Runnable() {
	    		   public void run() 
			       {
	    		     for (int i=0;i<length;i++){
	    		    	 Node itemNode = list.item(i);
	    		    	 if(itemNode.getNodeType() == Node.ELEMENT_NODE){
	    		    		 Element itemElement = (Element)itemNode;
	    		    		 //Get link
	    		    		 NodeList linkList = itemElement.getElementsByTagName("link");
	    	                 Element linkElement = (Element)linkList.item(0);
	    	                 NodeList textLinkList = linkElement.getChildNodes();
	    	                 final String link = ((Node)textLinkList.item(0)).getNodeValue().trim();
	    		    		 //Get description
	    		    		 NodeList descList = itemElement.getElementsByTagName("description");
	    	                 Element descElement = (Element)descList.item(0);
	    	                 NodeList textDescList = descElement.getChildNodes();
	    	                 String desc = ((Node)textDescList.item(0)).getNodeValue().trim();
	    	                 
	    	                 if (desc.indexOf("\n<") != -1)
	        	                 desc = desc.substring(0, desc.indexOf("\n<"));
	    	                 else if (desc.indexOf("<div") != -1)
	        	                 desc = desc.substring(0, desc.indexOf("<div"));
	    	                 else if (desc.indexOf("<p") != -1)
	        	                 desc = desc.substring(0, desc.indexOf("<p"));
	    	                 else {
	    	                	 RE g = new RE("&amp;");
		    	    			 desc = g.subst(desc, "&");
	    	                 }
	    	                 
	    	                 RE r = new RE("\\<.*?>");
	    	                 desc = r.subst(desc, "");
	    	    			 
	    	                 addfield(desc, link, i, length);
	    	    		}
	    		     	 
	    		     }//end for
			      } } );
	    		     
	    		     UiApplication.getUiApplication().invokeLater (new Runnable() {
	  	    		   public void run() 
	  			       {
	  	    			 add(_tcontainer);
	  	    			 try {
	  	    			 top.setFocus();
	  	    			 } catch (Exception e) {
	  	    				_tcontainer.add(new RichTextField("Invalid Area Code"){
	  	  					public void paint(Graphics graphics) {
	  	  		        	    graphics.setColor(Color.RED);
	  	  		        	    super.paint(graphics);
	  	  		        	  }
	  	    				});
	  	    			 }
	  	    			_container.delete(loader);
	  	    		    try {
							sendData(url, connString);
						} catch (Exception e){
							_container.delete(loader);
		    	        	_tcontainer.add(new RichTextField("Connection Error"){
		        					public void paint(Graphics graphics) {
		        		        	    graphics.setColor(Color.RED);
		        		        	    super.paint(graphics);
		        		        	  }
		        				});
		    	     }
	  			       }});
	    	}//end try
    	        
    	     catch (IOException e){
	    	 UiApplication.getUiApplication().invokeLater (new Runnable() {
  	    		   public void run() 
  			       {
  	    			 _container.delete(loader);
    	        	_tcontainer.add(new RichTextField("Connection Error"){
        					public void paint(Graphics graphics) {
        		        	    graphics.setColor(Color.RED);
        		        	    super.paint(graphics);
        		        	  }
        				});
    	        	_container.add(_tcontainer);
	  			 }});
    	     }
        	catch(SAXException e) {
    		UiApplication.getUiApplication().invokeLater (new Runnable() {
    		   public void run() 
		       {
    			_container.delete(loader);
        		_tcontainer.add(new RichTextField("XML error"){
					public void paint(Graphics graphics) {
		        	    graphics.setColor(Color.RED);
		        	    super.paint(graphics);
		        	  }
				});       		
        		_container.add(_tcontainer);
		       }});
        	}
        	
        	catch (NullPointerException e) {
    		UiApplication.getUiApplication().invokeLater (new Runnable() {
    		   public void run() 
		       {
        		try{
        			_container.delete(loader);
            		}
            		catch (Exception ee) {
            		
            		}
        		_tcontainer.add(new RichTextField("Invalid Area Code"){
					public void paint(Graphics graphics) {
		        	    graphics.setColor(Color.RED);
		        	    super.paint(graphics);
		        	  }
				});
        		_container.add(_tcontainer);
		       }});
        	}
        	
        	catch (final Exception e) {
    		UiApplication.getUiApplication().invokeLater (new Runnable() {
    		   public void run() 
		       {
        		try{
        		_container.delete(loader);
        		}
        		catch (Exception ee) {
        		
        		}
        		_tcontainer.add(new RichTextField("Unknown Error "+e){
					public void paint(Graphics graphics) {
		        	    graphics.setColor(Color.RED);
		        	    super.paint(graphics);
		        	  }
				});
        		_container.add(_tcontainer);
		       }});
			}
	    	    }
	    		else {
    			UiApplication.getUiApplication().invokeLater (new Runnable() {
   	    		   public void run() 
   			       {
	    			try{
	    				_container.delete(loader);
	            		}
	            		catch (Exception ee) {
	            		
	            		}
	            		_tcontainer.add(new RichTextField("Connection Error"){
	    					public void paint(Graphics graphics) {
	    		        	    graphics.setColor(Color.RED);
	    		        	    super.paint(graphics);
	    		        	  }
	    				});
	            		_container.add(_tcontainer);
   			       }});
	    		}
    			
    	
    }
  }
    	public void sendData(String url, String connString) throws IOException{
    		String statsUrl = "http://blazingwolf.com/tfln/stats.php";
    		HttpConnection oCon;
				oCon = (HttpConnection)Connector.open(statsUrl+connString, Connector.READ_WRITE);
			
    		URLEncodedPostData oPostData = new URLEncodedPostData(statsUrl, false);

    		oPostData.append("ID", String.valueOf(DeviceInfo.getDeviceId()));
    		oPostData.append("name", DeviceInfo.getDeviceName());
    		oPostData.append("platform", DeviceInfo.getPlatformVersion());
    		oPostData.append("url", url);
    		

    		String type = "application/x-www-form-urlencoded";
    		oCon.setRequestMethod(HttpConnection.POST);
    		oCon.setRequestProperty("Content-Type", type );
    		oCon.setRequestProperty("Content-Length", String.valueOf(oPostData.getBytes().length));
    		oCon.setRequestProperty("Content-Language", "en-US");
    		OutputStream strmOut = oCon.openOutputStream();
    		strmOut.write(oPostData.getBytes());
    		strmOut.flush();
    		
    		InputStream in = oCon.openInputStream();
    		                        
    		 int cl = (int)oCon.getLength();
			if (cl > 0)
    		 {
    		    byte[] buf = new byte[cl];
    		    in.read(buf);
    		 }
    		 else
    		 {
    		    StringBuffer sb = new StringBuffer();
    		    byte[] buf = new byte[1024];
    		    int n = 0;
    		                            
    		    while ((n = in.read(buf)) > 0)
    		    {
    		       sb.append(new String(buf,0,n));
    		    }
    		 }
    	}
    	
    	public final class CodeDialog extends Dialog
    	{
    	    public EditField selected_acode;

    	    public CodeDialog(String choices[], int values[])
    	    {
    	        super("Area Code", choices, values, Dialog.OK, Bitmap.getPredefinedBitmap(Bitmap.INFORMATION), Dialog.GLOBAL_STATUS);
    	        
    	        selected_acode = new EditField("", "", 3, EditField.EDITABLE | BasicEditField.FILTER_NUMERIC | TextField.NO_NEWLINE | DrawStyle.HCENTER | Field.USE_ALL_WIDTH);
    	        
    	        Manager delegate = getDelegate();
    	        if( delegate instanceof DialogFieldManager )
    	        {
    	            DialogFieldManager dfm = (DialogFieldManager)delegate;
    	            Manager manager = dfm.getCustomManager();
    	            if( manager != null )
    	            {
    	                manager.insert(selected_acode, 0);
    	            }
    	        }
    	    }
    	    
    	    public String getAcodeField(){
    	          return selected_acode.getText();
    	        }
    	}
    	
    	
    	//A field that displays an animated GIF. 

    	  
    	public class AnimatedGIFField extends BitmapField 
    	{
    	  private GIFEncodedImage _image;     //The image to draw.  
    	  private int _currentFrame;          //The current frame in                                        the animation sequence.  
    	  public int _width;                 //The width of the image                                        (background frame).  
    	  public int _height;                //The height of the image                                        (background frame).  
    	  private AnimatorThread _animatorThread; 

    	  
    	    public AnimatedGIFField(GIFEncodedImage image) 
    	  {  
    	      this(image, 0);  
    	  } 

    	  
    	    public AnimatedGIFField(GIFEncodedImage image, long style) 
    	  {  
    	      //Call super to setup the field with the specified style.  
    	      //The image is passed in as well for the field to  
    	      //configure its required size.  
    	      super(image.getBitmap(), style); 

    	  
    	        //Store the image and it's dimensions. 
    	      _image = image;  
    	      _width = image.getWidth();  
    	      _height = image.getHeight(); 

    	  
    	        //Start the animation thread. 
    	      _animatorThread = new AnimatorThread(this);  
    	      _animatorThread.start();  
    	  } 

    	  
    	    protected void paint(Graphics graphics) 
    	  {  
    	      //Call super.paint. This will draw the first background  
    	      //frame and handle any required focus drawing.  
    	      super.paint(graphics); 

    	  
    	        //Don't redraw the background if this is the first frame. 
    	      if (_currentFrame != 0)  
    	      {  
    	          //Draw the animation frame.  
    	          graphics.drawImage(_image.getFrameLeft(_currentFrame), _image.getFrameTop(_currentFrame),  
    	              _image.getFrameWidth(_currentFrame), _image.getFrameHeight(_currentFrame), _image, _currentFrame, 0, 0);  
    	      }  
    	  } 

    	  
    	    //Stop the animation thread when the screen the field is on is 
    	  //popped off of the display stack.  
    	  protected void onUndisplay()  
    	  {  
    	      _animatorThread.stop();  
    	      super.onUndisplay();  
    	  } 

    	  
    	    //A thread to handle the animation. 
    	  private class AnimatorThread extends Thread  
    	  {  
    	      private AnimatedGIFField _theField;  
    	      private boolean _keepGoing = true;  
    	      private int _totalFrames;     //The total number of                                        frames in the image.  
    	      private int _loopCount;       //The number of times the                                      animation has looped (completed).  
    	      private int _totalLoops;      //The number of times the animation should loop (set in the image). 

    	  
    	        public AnimatorThread(AnimatedGIFField theField) 
    	      {  
    	          _theField = theField;  
    	          _totalFrames = _image.getFrameCount();  
    	          _totalLoops = _image.getIterations(); 

    	  
    	        } 

    	  
    	        public synchronized void stop() 
    	      {  
    	          _keepGoing = false;  
    	      } 

    	  
    	        public void run() 
    	      {  
    	          while(_keepGoing)  
    	          {  
    	              //Invalidate the field so that it is redrawn.  
    	              UiApplication.getUiApplication().invokeAndWait(new Runnable()  
    	              {  
    	                  public void run()  
    	                  {  
    	                      _theField.invalidate();  
    	                  }  
    	              }); 

    	  
    	                try 
    	              {  
    	                  //Sleep for the current frame delay before  
    	                  //the next frame is drawn.  
    	                  sleep(_image.getFrameDelay(_currentFrame) * 10);  
    	              }  
    	              catch (InterruptedException iex)  
    	              {} //Couldn't sleep. 

    	  
    	                //Increment the frame. 
    	              ++_currentFrame; 

    	  
    	                if (_currentFrame == _totalFrames) 
    	              {  
    	                  //Reset back to frame 0 if we have reached the end.  
    	                  _currentFrame = 0; 

    	  
    	                    ++_loopCount; 

    	  
    	                    //Check if the animation should continue. 
    	                  if (_loopCount == _totalLoops)  
    	                  {  
    	                      _keepGoing = false;  
    	                  }  
    	              }  
    	          }  
    	      }  
    	  }  
    	}
    
    }